//
//  SCNSQLite3.swift
//  ShoucainuSwift
//
//  Created by 王家旭 on 2017/5/22.
//  Copyright © 2017年 Riluee. All rights reserved.
//

import Foundation
import SQLite

struct SCNSQLiteManager {
    
    var db: Connection!
    
    let userTable = Table("user")
    let memberid = Expression<String>("memberid")
    let username = Expression<String>("username")
    let nickname = Expression<String>("nickname")
    let ico = Expression<String>("ico")
    let tree = Expression<String>("tree")
    let moblie = Expression<String>("moblie")
    
    
    
    
    init() {
        createdsqlite3()
    }
    
    // 默认创建数据库
    mutating func createdsqlite3(filePath: String = "/Documents")  {
        
        let sqlFilePath = NSHomeDirectory() + filePath + "/SCN1.db"
//        print(sqlFilePath)
        do {
            db = try Connection(sqlFilePath)
            // 建表
            _ = try db.run(userTable.create(ifNotExists: true) { table in
                table.column(memberid, primaryKey: true)
                table.column(username)
                table.column(nickname)
                table.column(ico)
                table.column(tree)
                table.column(moblie)
            })
        } catch  {
            printLog(error)
        }
    }
    
    // 删除 userTable 表
    func delTable() {
        do {
            _ = try db.run(userTable.drop())
        } catch {
            printLog(error)
        }
        
    }
    // 读取数据
    func readTable() -> Dictionary<String, Any> {
        for user in try! db.prepare(userTable) {
            var tmp = [String:Any]()
            tmp["memberid"] = user[memberid]
            tmp["username"] = user[username]
            tmp["nickname"] = user[nickname]
            tmp["ico"] = user[ico]
            tmp["tree"] = user[tree]
            tmp["moblie"] = user[moblie]
            return tmp
        }
        return [:]
    }
    // 登录状态
    func isLogin() -> Bool {
        for user in try! db.prepare(userTable) {
            return !user[memberid].isEmpty
        }
        return false
    }
    // 领树后修改 tree 状态
    func updateTree(_ oldType: String,newType: String) {
        do {
           _ = try db.run(userTable.update(tree <- tree.replace(oldType, with: newType)))
        } catch {
            printLog(error)
        }
    }
}
